using UnityEngine;
using System;
using System.Collections;

public class DialogObject : MonoBehaviour {

	public DialogManager dialogCreate;
	public GameObject dialogElements;
	public TextMesh textDraw;
	public TextMesh nameTextMesh;
	public int characterLineLimit;
	public Renderer avatarRender;
	private int limitDialog;
	public Vector2 posXAvatar;
	int countString;
	public string sceneLoad;
	public string prefsSceneSave;
	private int count;
	
	void Start()
	{
		limitDialog = dialogCreate.dialogStateManager.Length;
		drawDialog();
	}
	
	void Update () 
	{
		if((Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)))
		{
			if(count < limitDialog)
			{

				drawDialog();
			}
			
			else
			{
				if(dialogElements)
				Destroy(dialogElements);
				
				Application.LoadLevel(sceneLoad);
				PlayerPrefs.SetString("Scene", prefsSceneSave	);
			}
		}

	}
	
	void drawDialog()
	{
		nameTextMesh.text = dialogCreate.dialogStateManager[count].name;
		avatarRender.material.mainTexture = dialogCreate.dialogStateManager[count].avatar;
		textDraw.text = "";
		
		countString = 0;
		
		if(dialogCreate.dialogStateManager[count].peopleType == DialogManager.dialogManager.peopleTalk.YOU)
		{
			Transform avatarRenderer = avatarRender.transform;
			avatarRenderer.position = new Vector3(posXAvatar.x,avatarRenderer.position.y,avatarRenderer.position.z);
		}
		else
		{
			Transform avatarRenderer = avatarRender.transform;
			avatarRenderer.position = new Vector3(posXAvatar.y,avatarRenderer.position.y,avatarRenderer.position.z);
		}
		
		string[] dialogMessages = dialogCreate.dialogStateManager[count].message.Split(' ');
		
		foreach(String newText in dialogMessages)
        {
        	char[] myChar = newText.ToCharArray();

            countString += (myChar.Length + 1);
			
            if(countString < characterLineLimit)
            {
            	textDraw.text += newText + " ";
            }
			
            else if(countString >= characterLineLimit)
            {
            	textDraw.text += "\n" + newText + " ";
                countString = (myChar.Length + 1);
            }
         }
		
		count ++;
		
	}

}
